<script setup lang="ts">
import { onMounted, reactive } from "vue";
import { BaseApi } from "@/apis/base.api";
import { UtilTool } from "@webxue/common";
import { useWebxRouteTabs } from "@webxue/vue3-antdv-ui";
import useForm from "@/hooks/useForm";
import useCusRouter from "@/hooks/useCusRouter";
import EventEmitTool from "@/utils/tools/event-emit.tool";

// 获取路由属性
const { router, routeQuery } = useCusRouter({
  queryKeys:[
    // 用户id
    "userId",
    // 是否只读
    "readonly"
  ]
});
const { addParentTab } = useWebxRouteTabs({ router });
// 获取详情hook
const { detailInfo, formRef, formState, onValidateFields, getFormRules } = useForm({
  // 获取表单数据
  formState: {} as Record<string, any>,
  // 获取详情数据
  async onInit() {
    if (!routeQuery.value.userId) return false;
    const response = await BaseApi.user.find({ id: routeQuery.value.userId });
    // 回显用户信息
    formState.value = UtilTool.lodash.cloneDeep(response.data);
    // 回显角色信息
    roleData.userRoleCodes = response.data.roleIds?.split(",") || [];
    return Promise.resolve(response);
  },
  // 表单校验成功回调
  async onValidateSuccess(values) {
    // 响应结果
    let response: Partial<ResponseData> = {};
    // 请求参数
    const requestBody: Record<string, any> = {
      nickName: values.nickName,
      loginCode: values.loginCode,
      email: values.email,
      mobile: values.mobile
    };
    if (routeQuery.value.userId) {
      // 编辑
      response = await BaseApi.user.update({
        ...requestBody,
        id: routeQuery.value.userId,
        roleList:  roleData.userRoleCodes.map(roleId => ({ roleId }))
      });
    } else {
      // 新增
      response = await BaseApi.user.save({
        ...requestBody,
        password: values.password,
        roleIds: roleData.userRoleCodes.join(",")
      });
    }
    if(response.success) {
      addParentTab();
    }
  }
})
// 获取默认密码
const defaultPassword = reactive({
  password:"",
  async set(){
    const response = await BaseApi.parameter.find({ configKey:"sys.default.password" });
    defaultPassword.password = response.data.configValue;
  }
});
// 角色管理
const roleData = reactive({
  roleList: [] as any[],
  userRoleCodes: [] as string[],
  async set(){
    const response = await BaseApi.role.list({ queryType:"all" });
    roleData.roleList = response.data;
  }
});

// form保存回调
EventEmitTool.on("FORM:SAVE", () => {
  // 开始校验
  onValidateFields();
});

onMounted(async () => {
  // 设置默认密码
  if(!routeQuery.value.userId) {
    await defaultPassword.set();
  }
  // 设置角色
  await roleData.set();
})
</script>

<template>
  <div>
    <WebxForm ref="formRef" :model="formState" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" :readonly="!!routeQuery.readonly">
      <div class="flex flex-col gap-2">
        <WebxCard :titleProps="{ title:'基本信息' }">
          <ARow class="px-2 pb-4" :gutter="[0, 10]">
            <ACol :span="8">
              <WebxFormItem label="昵称" name="nickName">
                <AInput v-model:value="formState.nickName" placeholder="请输入用户昵称" />
                <template #readonly>{{ formState.nickName }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="登录账号" name="loginCode" :rules="[{ required: true, message: '请输入用户登录账号' }]">
                <AInput v-model:value="formState.loginCode" placeholder="请输入用户登录账号" />
                <template #readonly>{{ formState.loginCode }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8" v-if="!routeQuery.userId">
              <AFormItem
                  label="登录密码"
                  name="password"
                  :rules="[{ required: true, message: '请输入用户登录密码', trigger: 'change' }]"
              >
                <WebxInputPwd :initPwd="defaultPassword.password" v-model:password="formState.password" />
              </AFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="邮箱" name="email">
                <AInput v-model:value="formState.email" placeholder="请输入用户邮箱" />
                <template #readonly>{{ formState.email }}</template>
              </WebxFormItem>
            </ACol>
            <ACol :span="8">
              <WebxFormItem label="手机号" name="mobile" :rules="getFormRules('mobile')">
                <AInput v-model:value="formState.mobile" placeholder="请输入用户手机号" />
                <template #readonly>{{ formState.mobile }}</template>
              </WebxFormItem>
            </ACol>
          </ARow>
        </WebxCard>
        <WebxCard :titleProps="{ title:'角色分配' }">
          <ACheckboxGroup v-model:value="roleData.userRoleCodes" :disabled="!!routeQuery.readonly">
            <ACheckbox v-for="role in roleData.roleList" :key="role.id" :value="role.id">
              {{ role.name }}
            </ACheckbox>
          </ACheckboxGroup>
        </WebxCard>
      </div>
    </WebxForm>
  </div>
</template>

<style scoped lang="less">
.ant-form-item {
  margin-bottom: 0;
}
</style>
